package com.roya.web.api;

import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.roya.common.ResultMap;
import com.roya.common.ResultMap.STATUS;
import com.roya.util.StringUtil;


@Controller("fileUploadController")
@RequestMapping("/api")
public class FileUploadController  extends BaseAction{

	@Value("#{settings['fileBaseDir']}")
	private String fileBaseDir;
	
	private Map<String,String> fileDir = new HashMap<String,String>();
	
	private List<String> allowList;
	
	@Value("#{settings['fileTypeDir']}")
	private String fileTypeDir;
	
	@Value("#{settings['fileAllowTypes']}")
	private String fileAllowTypes;
	
	Logger logger = Logger.getLogger(getClass());

	@RequestMapping("/fileUpload.shtml")
	public ResultMap fileUpload(HttpServletRequest request, HttpServletResponse response){
		ResultMap result = new ResultMap();
		String filePath = getFilePath(request);
		if(StringUtil.isNullOrEmptyStr(filePath)){
			log.warn("file type not exist!");
			result.setStatus(STATUS.ERROR);
			getJsonData(request,response,result);
			return null;
		}
		
		try{
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
			if(multipartResolver.isMultipart(request))
	        {
	            //将request变成多部分request
	            MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
	           //获取multiRequest 中所有的文件名
	            Map<String,MultipartFile> mutipartFileMap = multiRequest.getFileMap();
	             
	            Iterator<Entry<String, MultipartFile>> mutipartFileIterator =  mutipartFileMap.entrySet().iterator();
	            while(mutipartFileIterator.hasNext())
	            {
	            	Entry<String, MultipartFile> entry = mutipartFileIterator.next();
	                MultipartFile file=entry.getValue();
	                if(!isAllowFileType(file.getContentType())){
	                	log.error("upload file type error!");
	                	result.setStatus(STATUS.ERROR);
	        			getJsonData(request,response,result);
	        			return null;
	                }
	                if(file!=null && (!file.isEmpty()) &&  entry.getKey() !=null && entry.getKey().length()>0)
	                {
	                  	//目录
	                	StringBuffer fileFull = new StringBuffer();
	                	fileFull.append(fileBaseDir)
	                				.append(filePath)
	                				.append("/")
	                				.append(StringUtil.dateNowStr("yyyyMMdd"));
	                 	//文件
	                	StringBuffer fileFullPath = new StringBuffer(fileFull.toString());
	                	fileFullPath.append("/")
		        				.append(System.currentTimeMillis())
								.append(file.getOriginalFilename().replaceAll(" ", "").replaceAll(",", ""));
	                	
	                	//目录
	                	File dir = new File(fileFull.toString());
	                	if(!dir.exists()){
	                		dir.mkdirs();
	                	}
	                	//上传 文件
	                	File fileTmp = new File(fileFullPath.toString());

	        			if(!fileTmp.exists()){
	        				fileTmp.createNewFile();
	        				log.info("create new file !");
	        			}
	        			file.transferTo(fileTmp);
	        			
	        			result.setStatus(STATUS.SUCCESS);
	        			result.setAttribute("fileType", file.getContentType());
	        			result.setAttribute("fName",file.getOriginalFilename().replaceAll(" ", "").replaceAll(",", ""));
	        			result.setAttribute("fileUrl", fileFullPath.toString().substring(fileBaseDir.length())); 
	        			
	        			getJsonData(request,response,result);
	        			return null;
	                }
	                 
	            }
	           
	        }
		}catch(Exception e){
			log.error("upload file error:",e);
			result.setStatus(STATUS.ERROR);
			getJsonData(request,response,result);
			return null;
		}
		
		log.warn("no file upload!");
		result.setStatus(STATUS.ERROR);
		
		getJsonData(request,response,result);
		
		return null;
		
		
		
	}

	@Autowired
	private void setDir(){
		String[] fileTypes = fileTypeDir.split(";");
		for(String tmp : fileTypes){
			String[] tmpTypes = tmp.split(":");
			if(tmpTypes.length==2){
				fileDir.put(tmpTypes[0], tmpTypes[1]);
			}
		}
		
		//注入允许上传的文件类型
		allowList = new ArrayList<String>();
		String[] allowTypes = fileAllowTypes.split(",");
		for(String type : allowTypes){
			allowList.add(type);
		}
		
	}
	
	/**
	 * 
	 * @Title: getFilePath
	 * @Description: 根据文件类型选择上传文件路径 
	 * @param @param request
	 * @param @return   
	 * @return String   
	 * @throws
	 */
	private String getFilePath(HttpServletRequest request){
		String fileType = request.getParameter("fileType");
		if(StringUtil.isNullOrEmptyStr(fileType)){
			fileType = "common";
		}
		return fileDir.get(fileType);
	}
	
	/**
	 * 
	 * @Title: isAllowFileType
	 * @Description: 判断文件类型是否未允许的类型 
	 * @param @param type
	 * @param @return   
	 * @return boolean   
	 * @throws
	 */
	private boolean isAllowFileType(String type){
		return allowList.contains(type.toLowerCase());
	}
	private void getJsonData(HttpServletRequest request,HttpServletResponse response,Object result)
    {
        String callback = null;
        
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = null;
        
        if(result == null)
        {
            try
            {
                String jsonStr = "";
                out = response.getWriter();
                out.println(jsonStr);
            }
            catch (Exception e)
            {
            }
            finally
            {
                if (null != out)
                {
                    out.close();
                }
            }
        }
        
        try
        {
                
            JSONObject json = JSONObject.fromObject(result);
            String jsonStr = json.toString();
            if(!StringUtil.isNullOrEmptyStr(callback))
            {
                jsonStr =  callback + "("+ jsonStr +")";
            }
            
            
            out = response.getWriter();
            out.print(jsonStr);
        }
        catch (Exception e)
        {
        }
        finally
        {
            if (null != out)
            {
                out.close();
            }
        }
    }
}
